package cn.lili.xiaoran.controller;

import cn.lili.modules.goods.util.Generator;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.MemberPointsHistory;
import cn.lili.modules.member.entity.enums.PointTypeEnum;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.mapper.MemberPointsHistoryMapper;
import cn.lili.modules.member.service.MemberPointsHistoryService;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.search.entity.EsQuestionIndex;
import cn.lili.modules.search.service.EsGoodsIndexService;
import cn.lili.modules.search.service.EsGoodsSearchService;
import cn.lili.xiaoran.entity.*;
import cn.lili.xiaoran.entity.dtos.LiIndustryDTO;
import cn.lili.xiaoran.entity.dtos.LiQuestionsDTO;
import cn.lili.xiaoran.entity.vo.LiQuestionsDetailVo;
import cn.lili.xiaoran.mapper.LiIndustryMapper;
import cn.lili.xiaoran.mapper.LiQuestionsCollectionMapper;
import cn.lili.xiaoran.mapper.LiQuestionsDetailMapper;
import cn.lili.xiaoran.mapper.LiQuestionsFabulousMapper;
import cn.lili.xiaoran.service.LiIndustryService;
import cn.lili.xiaoran.service.LiQuestionsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.SearchVO;
import cn.lili.common.vo.ResultMessage;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javax.annotation.Resource;

/**
 * 提问表(LiQuestions)表控制层
 *
 * @author makejava
 * @since 2022-08-11 21:33:49
 */
@RestController
@Api(tags = "liQuestions接口")
@RequestMapping("/buyer/lili/liQuestions")
@Transactional(rollbackFor = Exception.class)
public class LiQuestionsController {
    /**
     * 服务对象
     */
    @Resource
    private LiQuestionsService liQuestionsService;

    @Resource
    private LiIndustryMapper liIndustryMapper;

    @Resource
    private LiQuestionsCollectionMapper liQuestionsCollectionMapper;

    @Resource
    private LiQuestionsFabulousMapper liQuestionsFabulousMapper;

    @Resource
    private LiQuestionsDetailMapper liQuestionsDetailMapper;

    @Resource
    private LiIndustryService liIndustryService;

    @Resource
    private MemberPointsHistoryMapper memberPointsHistoryMapper;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberPointsHistoryService memberPointsHistoryService;

    @Autowired
    private EsGoodsIndexService esGoodsIndexService;

    @GetMapping(value = "/{id}/{userId}")
    @ApiOperation(value = "查看${tableInfo.description}详情")
    public ResultMessage<LiQuestions> get(@PathVariable Integer id, @PathVariable String userId) {

        LiQuestions liQuestions = liQuestionsService.queryById(id);
        if(liQuestions.getUserId().equals(userId)){
//            QueryWrapper<LiQuestionsDetail> update=new QueryWrapper<>();
//            LiQuestionsDetail detail=new LiQuestionsDetail();
//            detail.setIsfaqirenweidu(false);
//            update.eq("questions_id",liQuestions.getId());
//            liQuestionsDetailMapper.update(detail,update);
            liQuestionsDetailMapper.updateweidu(liQuestions.getId());
        }
        LiIndustry liIndustry = liIndustryMapper.selectById(liQuestions.getIndustryId());
        liQuestions.setIndustryName(liIndustry.getIndustryName());
        liQuestions.setIndustryIcon(liIndustry.getIndustryIcon());
        //获取问题下的所有回答
        List<LiQuestionsDetailVo> details = liQuestionsDetailMapper.getDetailByQuestionId(liQuestions.getId());
        List<LiQuestionsDetailVo> fdetail = new ArrayList<>();
        Map<Integer, List<LiQuestionsDetailVo>> cdetailMap = new HashMap<>();
        QueryWrapper<LiQuestionsCollection> querySC = new QueryWrapper<>();
        querySC.in("questions_id", id);
        querySC.eq("type", 0);
        querySC.eq("delete_flag", 0);
        Long shoucancount = liQuestionsCollectionMapper.selectCount(querySC);
        querySC.eq("user_id", userId);
        List<LiQuestionsCollection> mysclist = liQuestionsCollectionMapper.selectList(querySC);
        if (mysclist.size() > 0) {
            liQuestions.setMysc(mysclist.get(0).getId());
        }
        liQuestions.setShoucang(Integer.parseInt(shoucancount + ""));
        QueryWrapper<LiQuestionsFabulous> queryDZ = new QueryWrapper<>();
        queryDZ.in("questions_id", id);
        queryDZ.eq("type", 0);
        queryDZ.eq("delete_flag", 0);
        Long dianzanshu = liQuestionsFabulousMapper.selectCount(queryDZ);
        queryDZ.eq("user_id", userId);
        List<LiQuestionsFabulous> dianzan = liQuestionsFabulousMapper.selectList(queryDZ);
        liQuestions.setDianzan(Integer.parseInt(dianzanshu + ""));
        if (dianzan.size() > 0) {
            liQuestions.setMydz(dianzan.get(0).getId());
        }
        List<String> userIds = new ArrayList<>();
        details.forEach(item -> {
            userIds.add(item.getUserId());
            fdetail.add(item);
//            if (item.getParentId() == null || item.getParentId() == 0) {
//                fdetail.add(item);
//            } else {
//                List<LiQuestionsDetailVo> list = new ArrayList<>();
//                if (cdetailMap.containsKey(item.getParentId())) {
//                    list = cdetailMap.get(item.getParentId());
//                }
//                list.add(item);
//                cdetailMap.put(item.getParentId(), list);
//            }
        });
        List<Member> members = new ArrayList<>();
        QueryWrapper<Member> memberQuery = new QueryWrapper<>();
        Map<String, Member> memberMap = new HashMap<>();
        if (userIds.size() > 0) {
            memberQuery.in("id", userIds);
            members = memberService.list(memberQuery);
            members.forEach(item -> {
                memberMap.put(item.getId(), item);
            });
        }

        List<Integer> detailIds = new ArrayList<>();
        fdetail.forEach(item -> {
            if (cdetailMap.containsKey(item.getId())) {
                item.setCdestais(cdetailMap.get(item.getId()));
            }
            detailIds.add(item.getId());
        });
        liQuestions.setShoucang(Integer.parseInt(shoucancount + ""));
        QueryWrapper<LiQuestionsFabulous> queryDZdetail = new QueryWrapper<>();
        queryDZdetail.in("questions_id", detailIds);
        queryDZdetail.eq("type", 1);
        queryDZdetail.eq("delete_flag", 0);
        List<LiQuestionsFabulous> dianzanList = new ArrayList<>();
        if (detailIds.size() > 0) {
            dianzanList = liQuestionsFabulousMapper.selectList(queryDZdetail);
        }

        Map<Integer, Integer> dzmap = new HashMap<>();
        Map<Integer, Integer> dzmapcount = new HashMap<>();
        dianzanList.forEach(item -> {
            if (item.getUserId().toString().equals(userId)) {
                dzmap.put(item.getQuestionsId(), item.getId());
            }
            int sccount = 0;
            if (dzmapcount.containsKey(item.getQuestionsId())) {
                sccount = dzmapcount.get(item.getQuestionsId());
            }
            sccount++;
            dzmapcount.put(item.getQuestionsId(), sccount);
        });
        QueryWrapper<LiQuestionsCollection> querySCDetails = new QueryWrapper<>();
        querySCDetails.in("questions_id", detailIds);
        querySCDetails.eq("type", 1);
        querySCDetails.eq("delete_flag", 0);
        List<LiQuestionsCollection> mysclistDetail = new ArrayList<>();
        if (detailIds.size() > 0) {
            mysclistDetail = liQuestionsCollectionMapper.selectList(querySC);
        }

        Map<Integer, Integer> scmap = new HashMap<>();
        Map<Integer, Integer> scmapcount = new HashMap<>();
        mysclistDetail.forEach(item -> {
            if (item.getUserId().toString().equals(userId)) {
                scmap.put(item.getQuestionsId(), item.getId());
            }
            int sccount = 0;
            if (scmapcount.containsKey(item.getQuestionsId())) {
                sccount = scmapcount.get(item.getQuestionsId());
            }
            sccount++;
            scmapcount.put(item.getQuestionsId(), sccount);
        });


        fdetail.forEach(item -> {
            item.setRenzhenglaoshi(false);
            if (memberMap.containsKey(item.getUserId() + "")) {
                item.setRenzhenglaoshi(memberMap.get(item.getUserId() + "").getIsRenzheng());
            }
            item.setShoucang(0);
            item.setDianzan(0);
            if (dzmapcount.containsKey(item.getId())) {
                item.setDianzan(dzmapcount.get(item.getId()));
            }
            if (scmapcount.containsKey(item.getId())) {
                item.setShoucang(scmapcount.get(item.getId()));
            }
            if (scmap.containsKey(item.getId())) {
                item.setMysc(scmap.get(item.getId()));
            }
            if (dzmap.containsKey(item.getId())) {
                item.setMydz(dzmap.get(item.getId()));
            }
        });
        fdetail.forEach(item->{
            if(item.getParentId()==null || item.getParentId()==0){
                diguiql(fdetail,item);
            }
        });
        List<LiQuestionsDetailVo>  newfdetail=fdetail.stream().filter(new Predicate<LiQuestionsDetailVo>() {
            @Override
            public boolean test(LiQuestionsDetailVo liQuestionsDetailVo) {
                return liQuestionsDetailVo.getParentId()==null || liQuestionsDetailVo.getParentId()==0;
            }
        }).collect(Collectors.toList());
        liQuestions.setDetails(newfdetail);
        int chakanshu = 0;
        if (liQuestions.getChakannum() != null) {
            chakanshu = liQuestions.getChakannum();
        }
        chakanshu++;
        liQuestions.setChakannum(chakanshu);
        liQuestionsService.updateById(liQuestions);

        return new ResultUtil<LiQuestions>().setData(liQuestions);
    }

    static public void diguiql(List<LiQuestionsDetailVo> pl,LiQuestionsDetailVo rootViewComment) {
        for (LiQuestionsDetailVo comment : pl) {
            // 找到匹配的 parentId
            if (rootViewComment.getId().equals(comment.getParentId())) {
//                BeanUtils.copyProperties(comment,viewComment);
                if(rootViewComment.getChildren()==null){
                    rootViewComment.setChildren(new ArrayList<>());
                }
                rootViewComment.getChildren().add(comment);
                //递归调用
                diguiql(pl,comment);
            }
        }
    }

    @GetMapping
    @ApiOperation(value = "分页获取${tableInfo.description}")
    public ResultMessage<IPage<LiQuestions>> getByPage(LiQuestionsDTO page) {
        IPage<LiQuestions> data = this.liQuestionsService.page(PageUtil.initPage(page), page.queryWrapper());
        List<Integer> industryList = new ArrayList<>();
        List<LiQuestions> list = data.getRecords();
        List<Integer> ids = new ArrayList<>();
        list.forEach(item -> {
            industryList.add(item.getIndustryId());
            ids.add(item.getId());
        });
        if (list.size() > 0) {
            QueryWrapper<LiIndustry> query = new QueryWrapper<>();
            query.in("id", industryList);

            List<LiIndustry> LiIndustrys = liIndustryMapper.selectList(query);
            Map<Integer, LiIndustry> map = new HashMap<>();
            LiIndustrys.forEach(item -> {
                map.put(item.getId(), item);
            });

            QueryWrapper<LiQuestionsCollection> querySC = new QueryWrapper<>();
            querySC.select(" if( count(id), count(id),0) as count,questions_id ");
            querySC.in("questions_id", ids);
            querySC.eq("type", 0);
            querySC.eq("delete_flag", 0);
            querySC.groupBy("questions_id");
            List<LiQuestionsCollection> shoucang = liQuestionsCollectionMapper.selectList(querySC);
            Map<Integer, Integer> scmap = new HashMap<>();
            shoucang.forEach(item -> {
                scmap.put(item.getQuestionsId(), item.getCount());
            });
            QueryWrapper<LiQuestionsFabulous> queryDZ = new QueryWrapper<>();
            queryDZ.select(" if( count(id), count(id),0) as count,questions_id ");
            queryDZ.in("questions_id", ids);
            queryDZ.eq("type", 0);
            queryDZ.eq("delete_flag", 0);
            queryDZ.groupBy("questions_id");
            List<LiQuestionsFabulous> dianzan = liQuestionsFabulousMapper.selectList(queryDZ);
            QueryWrapper<LiQuestionsDetail> queryDetail = new QueryWrapper<>();
            queryDetail.in("questions_id", ids);
            queryDetail.eq("delete_flag", 0);
//            queryDetail.groupBy("questions_id");
            queryDetail.orderByDesc("create_time");
            List<LiQuestionsDetail> details = liQuestionsDetailMapper.selectList(queryDetail);
            Map<Integer, LiQuestionsDetail> detailmap = new HashMap<>();
            Map<Integer, Integer> detailNummap = new HashMap<>();
            details.forEach(item -> {
                Integer num = 0;
                if (detailNummap.containsKey(item.getQuestionsId())) {
                    num = detailNummap.get(item.getQuestionsId());
                }
                num++;
                detailNummap.put(item.getQuestionsId(), num);
                detailmap.put(item.getQuestionsId(), item);
            });

            Map<Integer, Integer> dzmap = new HashMap<>();
            dianzan.forEach(item -> {
                dzmap.put(item.getQuestionsId(), item.getCount());
            });
            list.forEach(item -> {

                if (map.containsKey(item.getIndustryId())) {
                    item.setIndustryName(map.get(item.getIndustryId()).getIndustryName());
                }
                if (scmap.containsKey(item.getId())) {
                    item.setShoucang(scmap.get(item.getId()));
                }
                if (dzmap.containsKey(item.getId())) {
                    item.setDianzan(dzmap.get(item.getId()));
                }
                if (detailmap.containsKey(item.getId())) {
                    item.setDetail(detailmap.get(item.getId()));
                }
                item.setDetailNum(0);
                if (detailNummap.containsKey(item.getId())) {
                    item.setDetailNum(detailNummap.get(item.getId()));
                }
                if (item.getAppointUser() != null && item.getAppointUser().length() > 0) {
                    MemberVO info = memberService.getMember(item.getAppointUser() + "");
                    item.setAppointUserInfo(info);
                }
            });
            data.setRecords(list);
        }
        QueryWrapper<LiQuestionsDetail> qq = new QueryWrapper<>();
        qq.ne("user_id", 0);
        Long count = liQuestionsDetailMapper.selectCount(qq);
        data.setCurrent(count);
        return new ResultUtil<IPage<LiQuestions>>().setData(data);
    }

    @PostMapping
    @ApiOperation(value = "新增${tableInfo.description}")
    public ResultMessage<LiQuestions> save(LiQuestions liQuestions) throws Exception {
        liQuestions.setIsweidu(true);
        if (this.liQuestionsService.save(liQuestions)) {
            EsQuestionIndex index = Generator.convert(liQuestions, EsQuestionIndex.class);
            index.setDetails(new ArrayList<>());
            esGoodsIndexService.addIndex(index);
            return new ResultUtil<LiQuestions>().setData(liQuestions);
        }

        return new ResultUtil<LiQuestions>().setErrorMsg("未知异常，请稍后重试");
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "更新${entity.description}")
    public ResultMessage<LiQuestions> update(@PathVariable String id, LiQuestions liQuestions) {
        if (this.liQuestionsService.updateById(liQuestions)) {
            return new ResultUtil<LiQuestions>().setData(liQuestions);
        }
        return new ResultUtil<LiQuestions>().setErrorMsg("未知异常，请稍后重试");
    }

    @DeleteMapping(value = "/{ids}")
    @ApiOperation(value = "删除提问表")
    public ResultMessage<Object> delAllByIds(@PathVariable List ids) {

        liQuestionsService.removeByIds(ids);
        ids.forEach(id -> {
            MemberPointsHistory his = memberPointsHistoryMapper.getMemberPointsHistoryByType(2, Integer.parseInt(id.toString()));
            if (his != null) {
                memberPointsHistoryMapper.deleteById(his.getId());
            }
        });
        return ResultUtil.success("成功删除");
    }

    @GetMapping(value = "/getAllLiIndustry")
    @ApiOperation(value = "分页获取${tableInfo.description}")
    public ResultMessage<IPage<LiIndustry>> getByPage(LiIndustryDTO page) {
        IPage<LiIndustry> data = liIndustryService.page(PageUtil.initPage(page), page.queryWrapper());
        return new ResultUtil<IPage<LiIndustry>>().setData(data);
    }

    @GetMapping("/zhidingwodehuida")
    @ApiOperation(value = "分页获取${tableInfo.description}")
    public ResultMessage<IPage<LiQuestions>> zhidingwodehuida(LiQuestionsDTO page) {
        QueryWrapper<LiQuestions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("appoint_user", page.getAppointUser());
        queryWrapper.eq("is_zhidinghuida", 0);
        IPage<LiQuestions> data = this.liQuestionsService.page(PageUtil.initPage(page), queryWrapper);
        List<Integer> industryList = new ArrayList<>();
        List<LiQuestions> list = data.getRecords();
        List<Integer> ids = new ArrayList<>();
        list.forEach(item -> {
            industryList.add(item.getIndustryId());
            ids.add(item.getId());
        });
        if (list.size() > 0) {
            QueryWrapper<LiIndustry> query = new QueryWrapper<>();
            query.in("id", industryList);

            List<LiIndustry> LiIndustrys = liIndustryMapper.selectList(query);
            Map<Integer, LiIndustry> map = new HashMap<>();
            LiIndustrys.forEach(item -> {
                map.put(item.getId(), item);
            });

            QueryWrapper<LiQuestionsCollection> querySC = new QueryWrapper<>();
            querySC.select(" if( count(id), count(id),0) as count,questions_id ");
            querySC.in("questions_id", ids);
            querySC.eq("type", 0);
            querySC.eq("delete_flag", 0);
            querySC.groupBy("questions_id");
            List<LiQuestionsCollection> shoucang = liQuestionsCollectionMapper.selectList(querySC);
            Map<Integer, Integer> scmap = new HashMap<>();
            shoucang.forEach(item -> {
                scmap.put(item.getQuestionsId(), item.getCount());
            });
            QueryWrapper<LiQuestionsFabulous> queryDZ = new QueryWrapper<>();
            queryDZ.select(" if( count(id), count(id),0) as count,questions_id ");
            queryDZ.in("questions_id", ids);
            queryDZ.eq("type", 0);
            queryDZ.eq("delete_flag", 0);
            queryDZ.groupBy("questions_id");
            List<LiQuestionsFabulous> dianzan = liQuestionsFabulousMapper.selectList(queryDZ);
            QueryWrapper<LiQuestionsDetail> queryDetail = new QueryWrapper<>();
            queryDetail.in("questions_id", ids);
            queryDetail.eq("delete_flag", 0);
            queryDetail.groupBy("questions_id");
            queryDetail.orderByDesc("create_time");
            List<LiQuestionsDetail> details = liQuestionsDetailMapper.selectList(queryDetail);
            Map<Integer, LiQuestionsDetail> detailmap = new HashMap<>();
            Map<Integer, Integer> detailNummap = new HashMap<>();
            details.forEach(item -> {
                Integer num = 0;
                if (detailNummap.containsKey(item.getQuestionsId())) {
                    num = detailNummap.get(item.getQuestionsId());
                }
                num++;
                detailNummap.put(item.getQuestionsId(), num);
                detailmap.put(item.getQuestionsId(), item);
            });

            Map<Integer, Integer> dzmap = new HashMap<>();
            dianzan.forEach(item -> {
                dzmap.put(item.getQuestionsId(), item.getCount());
            });
            list.forEach(item -> {

                if (map.containsKey(item.getIndustryId())) {
                    item.setIndustryName(map.get(item.getIndustryId()).getIndustryName());
                }
                if (scmap.containsKey(item.getId())) {
                    item.setShoucang(scmap.get(item.getId()));
                }
                if (dzmap.containsKey(item.getId())) {
                    item.setDianzan(dzmap.get(item.getId()));
                }
                if (detailmap.containsKey(item.getId())) {
                    item.setDetail(detailmap.get(item.getId()));
                }
                item.setDetailNum(0);
                if (detailNummap.containsKey(item.getId())) {
                    item.setDetailNum(detailNummap.get(item.getId()));
                }
                if (item.getAppointUser() != null) {
                    MemberVO info = memberService.getMember(item.getAppointUser() + "");
                    item.setAppointUserInfo(info);
                }
            });
            data.setRecords(list);
        }
        QueryWrapper<LiQuestionsDetail> qq = new QueryWrapper<>();
        qq.ne("user_id", 0);
        Long count = liQuestionsDetailMapper.selectCount(qq);
        data.setCurrent(count);
        return new ResultUtil<IPage<LiQuestions>>().setData(data);
    }

}

